import {
    Component,
    ViewChild,
    Injector,
    Output,
    EventEmitter,
    ElementRef,
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { AppComponentBase } from '@shared/common/app-component-base';

import * as moment from 'moment';
import { finalize } from 'rxjs/operators';
import {
    ProcWorkingTimeInput,
    UserWorkingTimeServiceProxy,
    OrganizationUnitServiceProxy,
    ComboboxItemDto,
} from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/api';

@Component({
    selector: 'createProcModal',
    styleUrls: ['./create-proc-modal.component.less'],
    templateUrl: './create-proc-modal.component.html',
})
export class CreateProcModalComponent extends AppComponentBase {
    @ViewChild('actionModal') modal: ModalDirective;
    @ViewChild('dueDatePicker') dueDatePicker: ElementRef;
    @ViewChild('tmplCombobox') tmplCombobox: ElementRef;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    proc: ProcWorkingTimeInput;
    teamGroups: ComboboxItemDto[] = [];
    teamGroupName: ComboboxItemDto;
    event: LazyLoadEvent;
    constructor(
        injector: Injector,
        private _userWorkingTimeServiceProxy: UserWorkingTimeServiceProxy,
        private _organization: OrganizationUnitServiceProxy
    ) {
        super(injector);
    }

    show(id?: string, event?: LazyLoadEvent): void {
        this.active = true;
        this.proc = new ProcWorkingTimeInput();
        this.event = event;
        this._organization
            .getTeamGroups()
            .pipe()
            .subscribe((result) => {
                this.teamGroups = result.items;
            });
        if (id != null || id != '') {
            this._userWorkingTimeServiceProxy
                .getProcForEdit(id)
                .subscribe((result) => {
                    this.proc = result;
                    this.teamGroupName = this.teamGroups.find(
                        (p) => p.displayText == result.orgName
                    );
                });
        }

        this.modal.show();
    }

    save(): void {
        this.saving = true;
        this.proc.orgName = this.teamGroupName.displayText;
        if (this.proc.totalProcWorkingTime <= 0) {
            this.saving = false;
            this.notify.error('工序工时必须大于0');
        } else {
            this._userWorkingTimeServiceProxy
                .createOrUpdateProWorkingTime(this.proc)
                .pipe(
                    finalize(() => {
                        this.saving = false;
                    })
                )
                .subscribe((result) => {
                    this.notify.info('保存成功');
                    this.close();
                    this.modalSave.emit(null);
                });
        }
    }

    close(): void {
        this.saving = false;
        this.modal.hide();
    }
}
